package com.sztle.admodule.control.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;

public class HashUtils {
	private static HashMap<String, String> uniqueStringsMap = new HashMap<>();

	// Base62编码字符集
	private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();

	public static String generateUnique16CharString(String input) throws NoSuchAlgorithmException {
		try {

		}catch (Exception e){

		}
		String shortStr = hashAndEncode(input);
		// 检查是否已存在
		while (uniqueStringsMap.containsValue(shortStr)) {
			// 如果存在，修改输入字符串，重新生成
			input += System.nanoTime(); // 或者添加其他唯一性的东西
			shortStr = hashAndEncode(input);
		}
		uniqueStringsMap.put(input, shortStr);
		return shortStr;
	}

	public static String hashAndEncode(String input) {
		// 使用SHA-256哈希函数
		if (TextUtils.isEmpty(input)) {
			return "unkown";
		}
		input = input.replace("-","").trim();
		String result = input;
		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(input.getBytes());

			// 转换为Base62编码字符串
			String encoded = base62Encode(hash);
			result = encoded.substring(0, 16).toLowerCase();
		} catch (NoSuchAlgorithmException exception) {

		}


		// 截取前16个字符
		return result;
	}

	public static String getMd5Str(String input) {
		// 使用SHA-256哈希函数
		if (TextUtils.isEmpty(input)) {
			return "unkown";
		}
		input = input.replace("-","").trim();
		String result = input;
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] hash = digest.digest(input.getBytes());

			// 转换为Base62编码字符串
			String encoded = base62Encode(hash);
			result = encoded.substring(0, 16).toLowerCase();
		} catch (NoSuchAlgorithmException exception) {

		}


		// 截取前16个字符
		return result;
	}

	private static String base62Encode(byte[] input) {
		StringBuilder sb = new StringBuilder();
		int index;
		int value = 0;
		int bits = 0;
		for (byte b : input) {
			value = (value << 8) | (b & 0xFF);
			bits += 8;
			while (bits >= 6) {
				bits -= 6;
				index = (value >> bits) & 0x3F;
				// 确保索引在0到61之间
				if (index >= 62) {
					index = index % 62;
				}
				sb.append(BASE62[index]);
			}
		}
		if (bits > 0) {
			// 处理剩余的位
			value <<= (6 - bits);
			index = value & 0x3F;
			if (index >= 62) {
				index = index % 62;
			}
			sb.append(BASE62[index]);
		}
		return sb.toString();
	}
}